package cn.car.web.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.car.entity.Admin;
import cn.car.entity.Car;
import cn.car.entity.Order;
import cn.car.entity.Type;
import cn.car.entity.User;
import cn.car.service.AdminService;
import cn.car.service.CarService;
import cn.car.service.OrderService;
import cn.car.service.TypeService;
import cn.car.service.UserService;

@Controller
@RequestMapping("/admin")
public class AdminAction {

	@Resource
	private AdminService adminService;
	@Resource
	private CarService carService;
	@Resource
	private UserService userService;
	@Resource
	private OrderService orderService;
	@Resource
	private TypeService typeService;
	
	@RequestMapping("/loginUI")
	public String loginUI(){
		return "/WEB-INF/admin/loginUI.jsp";
	}
	
	@RequestMapping("/carCansus")
	public String carCansusUI(){
		return "/WEB-INF/admin/analyze/carCansus.jsp";
	}
	
	@RequestMapping("/newUser")
	public String newUserUI(){
		return "/WEB-INF/admin/analyze/newUser.jsp";
	}
	
	@RequestMapping(value="/login")
	public String login(String account,String password,HttpSession session,HttpServletRequest request){
		Admin admin = adminService.login(account, password);
		if(admin!=null){
			session.setAttribute("ADMININFO", admin);
			return "/WEB-INF/admin/index.jsp";
		}else{
			request.setAttribute("msg", "请检查用户名或者密码是否正确");
			return "/WEB-INF/admin/loginUI.jsp";
		}
	}
	
	@RequestMapping(value="/quit")
	public String quit(HttpSession session){
		session.removeAttribute("ADMININFO");
		return "/WEB-INF/admin/loginUI.jsp";
	}
	
	/**
	 * 跳转车辆列表页面 
	 * @return
	 */
	@RequestMapping(value="/carList")
	public String carList(Model model){
		List<Car> cars = carService.findObjects();
		model.addAttribute("cars", cars);
		return "/WEB-INF/admin/car/carList.jsp";
	}
	
	/**
	 * 跳转用户列表页面 
	 * @return
	 */
	@RequestMapping(value="/userList")
	public String userList(Model model){
		List<User> users = userService.findObjects();
		model.addAttribute("users", users);
		return "/WEB-INF/admin/user/userList.jsp";
	}
	
	/**
	 * 跳转订单列表页面 
	 * 如果有带用户id过来,则返回用户的订单
	 * 若没有返回全部的订单
	 * @return
	 */
	@RequestMapping(value="/orderListUI")
	public String orderList(Model model,String uid){
		List<Order> orders = null;
		if(uid!=null && !"".equals(uid)){
			orders = orderService.findObjectByUser(uid);
		}else{
			orders = orderService.findObjects();
		}
		model.addAttribute("orders", orders);
		model.addAttribute("uid", uid);
		return "/WEB-INF/admin/order/orderList.jsp";
	}
	
	/**
	 * 跳转到订单详细页面
	 * @return
	 */
	@RequestMapping(value="/orderDetailUI")
	public String orderDetailUI(String oid,Model model,String uid){
		Order order = orderService.findObjectById(oid);
		model.addAttribute("order", order);
		model.addAttribute("uid",uid);
		return "/WEB-INF/admin/order/orderDetail.jsp";
	}
	
	/**
	 * 跳转到车辆详细页面
	 * @return
	 */
	@RequestMapping(value="/userDetailUI")
	public String userDetailUI(String uid,Model model){
		User user = userService.findObjectById(uid);
		model.addAttribute("user", user);
		return "/WEB-INF/admin/user/userDetail.jsp";
	}
	
	/**
	 * 跳转到新增车辆页面
	 * @return
	 */
	@RequestMapping(value="/carNewUI")
	public String carNewUI(){
		return "/WEB-INF/admin/car/carNew.jsp";
	}
	
	/**
	 * 保存新增车辆
	 * @param car
	 * @param request
	 * @param file
	 * @return
	 */
	@RequestMapping(value="/addCar")
	public String addCar(Car car,HttpServletRequest request,@RequestParam(value ="file",required = false) MultipartFile file){
		
		String path = request.getSession().getServletContext().getRealPath("upload/car");
		String fileName = file.getOriginalFilename();
		fileName = System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
		File targetFile = new File(path,fileName);
		//保存
		try{
			file.transferTo(targetFile);
		}catch (Exception e) {
			e.printStackTrace();
		}
		car.setReleaseTime(new Date());
		car.setImage(request.getContextPath()+"/upload/car/"+fileName);
		carService.save(car);
		return "redirect:/admin/carList.action";
	}
	
	/**
	 * 跳转到车辆详细页面
	 * @return
	 */
	@RequestMapping(value="/carDetailUI")
	public String carDetailUI(String cid,Model model){
		Car car = carService.findObjectById(cid);
		model.addAttribute("car", car);
		return "/WEB-INF/admin/car/carDetail.jsp";
	}
	
	/**
	 * 跳转到车辆修改页面
	 * @return
	 */
	@RequestMapping(value="/carModifyUI")
	public String carModifyUI(String cid,Model model){
		Car car = carService.findObjectById(cid);
		List<Type> types = typeService.findObjects();
		model.addAttribute("car", car);
		model.addAttribute("types", types);
		return "/WEB-INF/admin/car/carModify.jsp";
	}
	
	
	
	/**
	 * 保存新增车辆
	 * @param car
	 * @param request
	 * @param file
	 * @return
	 */
	@RequestMapping(value="/modifyCar")
	public String modifyCar(Car car,HttpServletRequest request,@RequestParam(value ="file",required = false) MultipartFile file){
		if(file!=null){
			try{
				String path = request.getSession().getServletContext().getRealPath("upload/car");
				String fileName = file.getOriginalFilename();
				fileName = System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
				File targetFile = new File(path,fileName);
				car.setImage(request.getContextPath()+"/upload/car/"+fileName);
			//保存
				file.transferTo(targetFile);
			}catch (Exception e) {
				
			}
		}
		carService.update(car);
		return "redirect:/admin/carList.action";
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(
				Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}

	/**
	 * 异步获取车辆集合
	 * 根据车辆种类
	 * @param typeid 
	 * @return
	 */
	@RequestMapping("/ajaxGetCars")
	@ResponseBody
	public Map<String, Object> ajaxGetCars(String typeid){
		List<Car> cars = carService.findObjectByType(typeid);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("msg", "成功");
		map.put("cars", cars);
		return map;
	}
	
	/**
	 * 异步获取订单集合
	 * 根据订单状态和用户id
	 * @param typeid 
	 * @return
	 */
	@RequestMapping("/ajaxGetOrders")
	@ResponseBody
	public Map<String, Object> ajaxGetOrder(String state,String uid){
		List<Order> orders = orderService.findObjectByStateOrUser(state,uid);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("msg", "成功");
		map.put("orders", orders);
		return map;
	}
	
	/**
	 * 异步改变订单状态
	 * 根据订单状态
	 * @param typeid 
	 * @return
	 */
	@RequestMapping("/ajaxModifyState")
	public void ajaxModifyState(String sid,String state){
		orderService.changeOrderState(sid,state);
	}
}
 